package com.ztz.mynewdemo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.headerfooter.songhang.library.SmartRecyclerAdapter;
import com.rd.PageIndicatorView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.ztz.mynewdemo.R;
import com.ztz.mynewdemo.activity.CarouselActivity;
import com.ztz.mynewdemo.activity.ContentActivity;
import com.ztz.mynewdemo.activity.PhotoAcitivy;
import com.ztz.mynewdemo.adapter.BannerAdapter;
import com.ztz.mynewdemo.adapter.zhuKuAdapter;
import com.ztz.mynewdemo.utils.Constants;
import com.ztz.mynewdemo.utils.GlideImageLoader;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG;

/**
 * Created by wqewqe on 2017/12/20.
 */

public class ZhanKuFragment extends BaseFragment {
    ArrayList<String> titles = new ArrayList<>();
    ArrayList<String> detailUris = new ArrayList<>();
    ArrayList<String> imgUris = new ArrayList<>();
    ArrayList<String> smTitles = new ArrayList<>();
    ArrayList<String> carouselViews = new ArrayList<>();
    ArrayList<String> carouselWeb = new ArrayList<>();
    @BindView(R.id.rl)
    RecyclerView rl;
    @BindView(R.id.top)
    FloatingActionButton top;
    Unbinder unbinder;
    BannerAdapter bannerAdapter;
    zhuKuAdapter adapter;
    ViewPager vp;
    ScheduledExecutorService scheduledExecutorService;
    SmartRefreshLayout refreshLayout;
    PageIndicatorView pageIndicatorView;
    private float ratio;
    private Banner banner;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_zhuku, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //获取图片资源与屏幕的比列
        ratio = 1F * (getResources().getDisplayMetrics().heightPixels / 1920.0F);
        refreshLayout = (SmartRefreshLayout) view.findViewById(R.id.zhuku_Smart);
        setRefresh();
        rl.setLayoutManager(new GridLayoutManager(getContext(), 3));
        adapter = new zhuKuAdapter(getContext(), titles, imgUris, smTitles);
        SmartRecyclerAdapter smartRecyclerAdapter = new SmartRecyclerAdapter(adapter);
        View headView = LayoutInflater.from(getContext()).inflate(R.layout.layout_headview, null);
        vp = (ViewPager) headView.findViewById(R.id.vp_head);
        banner= (Banner) headView.findViewById(R.id.head_banner);
        smartRecyclerAdapter.setHeaderView(headView);
        //设置banner样式
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(carouselViews);
        //设置动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(carouselViews.size()*400);
        //设置指示器位置
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(position -> {
            Intent intent = new Intent(getActivity(), CarouselActivity.class);
            intent.putExtra(CarouselActivity.WEB_VIEW, carouselWeb.get(position));
            startActivity(intent);
        });
        banner.start();
        bannerAdapter = new BannerAdapter(carouselViews, getContext());
        vp.setAdapter(bannerAdapter);
        rl.setAdapter(smartRecyclerAdapter);
        adapter.setImageShow(new zhuKuAdapter.ImageShow() {
            @Override
            public void showImage(int position) {
                Intent intent = new Intent(getActivity(), PhotoAcitivy.class);
                intent.putExtra(PhotoAcitivy.PHOTO, imgUris.get(position));
                startActivity(intent);
            }

            @Override
            public void showDetail(int position) {
                Intent intent = new Intent(getActivity(), ContentActivity.class);
                intent.putExtra(ContentActivity.CONTENT, detailUris.get(position));
                intent.putExtra(ContentActivity.TITLES,titles.get(position));
                startActivity(intent);
            }
        });
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case 1:
                        stop();
                        break;
                    case 2:
                        if (scheduledExecutorService == null) {
                            run();
                        }
                        break;
                }
            }
        });
        run();
        bannerAdapter.setCariousShow(new BannerAdapter.CariousShow() {
            @Override
            public void showView(int position) {
                Intent intent = new Intent(getActivity(), CarouselActivity.class);
                intent.putExtra(CarouselActivity.WEB_VIEW, carouselWeb.get(position));
                startActivity(intent);
            }
        });
        pageIndicatorView = (PageIndicatorView) headView.findViewById(R.id.pageIndicatorView);
        pageIndicatorView.setViewPager(vp);
        pageIndicatorView.setRadius(12F * ratio);
        pageIndicatorView.setPadding((int) (5 * ratio), 0, (int) (5 * ratio), 0);
    }
    @Override
    public void onResume() {
        super.onResume();
        if (banner != null) {
            banner.startAutoPlay();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (banner != null) {
            banner.stopAutoPlay();
        }
    }
    private void setRefresh(){
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            refreshLayout.finishRefresh(1500);
            setRefreshThemeColor();
        });
        refreshLayout.setOnLoadMoreListener(refreshLayout -> refreshLayout.finishLoadMore(1500));
    }
    private int themeCount;
    private void setRefreshThemeColor() {
        themeCount++;
        if (themeCount % Constants.FOUR == Constants.ONE) {
            refreshLayout.setPrimaryColorsId(Constants.BLUE_THEME, R.color.white);
        } else if (themeCount % Constants.FOUR == Constants.TWO) {
            refreshLayout.setPrimaryColorsId(Constants.GREEN_THEME, R.color.white);
        } else if (themeCount % Constants.FOUR == Constants.THREE) {
            refreshLayout.setPrimaryColorsId(Constants.RED_THEME, R.color.white);
        } else if (themeCount % Constants.FOUR == Constants.ZERO) {
            refreshLayout.setPrimaryColorsId(Constants.ORANGE_THEME, R.color.white);
        }
    }
    public void run() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(new ViewTask(), 2, 2, TimeUnit.SECONDS);
    }

    int currentItem = 0;

    @Override
    protected void getData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    parsingData();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //转到主线程进行UI更新
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        bannerAdapter.notifyDataSetChanged();
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
    }

    class ViewTask implements Runnable {

        @Override
        public void run() {
            currentItem = (currentItem + 1) % carouselViews.size();
            handler.sendEmptyMessage(0);
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            vp.setCurrentItem(currentItem);
        }
    };

    private void stop() {
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
            scheduledExecutorService = null;
        }
    }

    private void parsingData() throws IOException {
        Document document = Jsoup.connect("http://www.zcool.com.cn/").get();
        Log.e(TAG, "parsingData: " + document.title());
        Elements slide_container = document.getElementsByClass("slider-adv-box");
//        Log.e(TAG, "parsingData: "+slide_container);
        for (Element slide : slide_container) {
            Elements container = slide.getElementsByTag("ul");
//            Log.e(TAG, "parsingData: "+container);
            Elements li = container.first().getElementsByTag("li");
//            Log.e(TAG, "parsingData: "+li);
            for (Element e : li) {
                Element a = e.getElementsByTag("a").first();
                Element a1 = a.after("a");
                System.out.println("轮播图网站链接: " + a1.attr("href"));
                carouselWeb.add(a1.attr("href"));
                Element img = e.getElementsByTag("img").first();
                Element img1 = img.after("img");
                System.out.println("轮播图图片链接: " + img1.attr("src"));
                carouselViews.add(img1.attr("src"));
            }
        }
//        Elements li = slide_contanier.first().getElementsByTag("li");
//        for (Element e : li) {
//            Element img = e.getElementsByTag("img").first();
//            Element img1 = img.after("img");
//            System.out.println("轮播图链接: "+img1.attr("src"));
//        }
        Elements work_list = document.getElementsByClass("work-list-box");
        Elements card = work_list.first().getElementsByClass("card-box");
        for (Element e : card) {
            Elements card_image = e.getElementsByClass("card-img");
            for (Element cd : card_image) {
                Element first = cd.getElementsByClass("card-img-hover").first();
                Element a = first.after("a");
                titles.add(a.attr("title"));
                detailUris.add(a.attr("href"));
//                System.out.println("标题为: "+a.attr("title"));
//                System.out.println("详情界面链接: "+a.attr("href"));
                Element img = cd.getElementsByTag("img").first();
                Element img1 = img.after("img");
                imgUris.add(img1.attr("src"));
//                Log.e(TAG, "图片链接: "+img1.attr("src"));
            }
            Elements card_info = e.getElementsByClass("card-info");
            for (Element info : card_info) {
                Element type_first = info.getElementsByClass("card-info-type").first();
                Element p = type_first.after("p");
//                System.out.println("小标题: "+p.text());
                smTitles.add(p.text());
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.top)
    public void onViewClicked() {
        rl.smoothScrollToPosition(0);
    }
}
